<template>
  <div class="visualization">
    <side-graph-panel v-if="!isFullMode" />
    <div
      class="view-box"
      :class="{
        open: settingPanelIsOpen,
        close: !settingPanelIsOpen,
        'hide-chart-panel': isFullMode,
      }"
    >
      <div ref="pipelineAndEdit" class="layout-container">
        <preview-pipeline
          ref="graph"
          :style="{
            height: showPreviewPipeline
              ? `calc(100% - ${modelOfVisualizationHeight}px)`
              : '0',
          }"
          :project-id="projectId"
          :pipeline-id="pipelineId"
        />
        <div
          class="panel-content"
          :style="{
            height: showPreviewPipeline
              ? `${modelOfVisualizationHeight}px`
              : '100%',
          }"
        >
          <!-- <tabs
            v-if="tabs.length >= 1"
            ref="tab"
            v-model="activeSystem"
            :min-hidden-width="120"
            :tabs="tabs"
            :allowed-edit="tru"
            :allowed-delete="true"
            :lock-mode="false"
            @check="changeSystem"
            @add="addTab"
            @remove="removeTab"
          >
          </tabs> -->
          <div
            class="resize-panel-content-height"
            @mousedown="resizeLogHeight($event)"
          ></div>
          <visualization-content
            :project-id="projectId"
            @toggle-pipeline="togglePipeline"
          />
          <div
            v-show="modelOfVisualizationHeight > 100"
            class="control-setter-box"
          >
            <side-graph-setting
              :graph-is-open="settingPanelIsOpen"
              @toggleSettingPanel="toggleSettingPanel"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import VisualizationStore from '@/store/modules/visualization'
import VisualizationContent from '@/components/visualization/VisualizationContent.vue'
import SideGraphSetting from '@/components/visualization/SideGraphSetting.vue'
import SideGraphPanel from '@/components/visualization/SideGraphPanel.vue'
import PreviewPipeline from '@/components/visualization/PreviewPipeline.vue'
import DataViewStore from '@/store/modules/dataview'
import Tabs from '@/components/studio/data/graph-compoments/Tabs.vue'
import { pipelineList } from '@/api/pipeline'
import { queryDatalist } from '@/api/studio'
import { debounce } from 'lodash'

@Component({
  components: {
    VisualizationContent,
    SideGraphSetting,
    SideGraphPanel,
    PreviewPipeline,
    Tabs,
  },
})
export default class VisualizationView extends Vue {
  public tabs: any[] = [
    {
      data: { key: 'value' },
      id: 1115,
      name: 'New Tab',
      projectId: 498,
      userId: 137,
      userName: '系统 1',
    },
  ]
  public activeSystem: number = 1115
  public pipelineId: number = 0
  public projectId: number = 0
  private showPreviewPipeline: boolean = false

  public beforeCreated() {
    this.getPipelineList()
  }

  public created() {
    this.projectId = Number(this.$route.params.id)
    DataViewStore.setProjectId(this.projectId)
    if (DataViewStore.getPipelineId !== null) {
      this.pipelineId = DataViewStore.getPipelineId
    } else {
      this.getPipelineList()
    }
    this.fetchDatasetList()
  }

  public mounted() {
    window.addEventListener('resize', this.handleResize)
  }

  private destroyed() {
    window.removeEventListener('resize', this.handleResize)
  }

  private handleResize = debounce(() => this._handleResize(), 300)

  private _handleResize() {
    if (this.showPreviewPipeline) {
      this.modelOfVisualizationHeight = (document.body.clientHeight - 64) * 0.6
    } else {
      this.modelOfVisualizationHeight = document.body.clientHeight - 64
    }
  }

  /**
   * 获取 pipeline 列表
   */
  public async getPipelineList() {
    const parameters = {
      projectId: this.projectId,
    }

    pipelineList({ data: parameters })?.then((response: any) => {
      if (response.data.code === 100) {
        const panes = response.data.result
        if (panes.length > 0) {
          this.pipelineId = panes[0].id
          DataViewStore.setPipelineId(this.pipelineId)
        }
      }
    })
  }

  public get settingPanelIsOpen() {
    return VisualizationStore.settingPanelIsOpen
  }

  public get isFullMode() {
    return VisualizationStore.isFullMode
  }

  public toggleSettingPanel() {
    VisualizationStore.setSettingPanelIsOpen(!this.settingPanelIsOpen)
  }

  public togglePipeline() {
    if (this.modelOfVisualizationHeight < document.body.clientHeight - 64) {
      this.modelOfVisualizationHeight = document.body.clientHeight - 64
    } else {
      this.modelOfVisualizationHeight = (document.body.clientHeight - 64) * 0.6
    }
    this.showPreviewPipeline = !this.showPreviewPipeline
  }

  // ------------------------Tab start--------------------------
  public addTab() {
    this.tabs.push({
      data: { key: 'value' },
      id: this.tabs[this.tabs.length - 1].id + 1,
      name: 'New Tab',
      projectId: this.projectId,
      userId: 137,
      userName: `系统 ${
        Number(this.tabs[this.tabs.length - 1].userName.split(' ')[1]) + 1
      }`,
    })
    this.activeSystem = this.tabs[this.tabs.length - 1].id
  }

  public removeTab(systemId: number) {
    this.tabs.splice(
      this.tabs.findIndex((item: any) => item.id === systemId),
      1
    )
    this.activeSystem = this.tabs[this.tabs.length - 1].id
  }

  public changeSystem(systemId: number) {
    this.activeSystem = systemId
  }
  // ------------------------Tab end--------------------------

  // --------------改变画板高度部分----------------------------------
  private editPanelMaxHeight: number = 0 // 画板模块最大高度
  public mouseLastPosition = { x: 0, y: 0 }
  // 节点编辑面板是否在拖动改变高度
  public isNodeEditModuleDragged: boolean = false
  // 画板高度
  public modelOfVisualizationHeight: any = document.body.clientHeight - 64
  // public modelOfVisualizationHeight: any = (document.body.clientHeight-64)*0.6
  // public modelOfVisualizationHeight: any = document.body.clientHeight-64-219
  /**
   * 改变画板模块高度
   */
  public resizeLogHeight($event: MouseEvent) {
    if (this.showPreviewPipeline) {
      $event.stopPropagation()
      this.editPanelMaxHeight = (this.$refs
        .pipelineAndEdit as HTMLElement).getBoundingClientRect().height
      this.mouseLastPosition = { x: $event.screenX, y: $event.screenY }
      this.isNodeEditModuleDragged = true
      document.addEventListener('mouseup', this.dragMouseUpListener)
      document.addEventListener('mousemove', this.dragMouseMoveListener)
    }
  }

  public async dragMouseUpListener() {
    const reference: any = this.$refs.graph as Vue
    reference.initVariable()
    document.removeEventListener('mousemove', this.dragMouseMoveListener)
    document.removeEventListener('mouseup', this.dragMouseUpListener)
    // 保存高度
    // DataViewStore.setNodeEditPanelHeight(this.modelOfVisualizationHeight)
    this.isNodeEditModuleDragged = false
  }

  public dragMouseMoveListener({ screenX, screenY }: MouseEvent) {
    const dy = screenY - this.mouseLastPosition.y
    this.$nextTick(() => {
      if (
        this.modelOfVisualizationHeight >= 46 &&
        this.modelOfVisualizationHeight <= this.editPanelMaxHeight
      ) {
        let height: number = this.modelOfVisualizationHeight - dy
        if (height < 46) {
          height = 46
        }
        if (height > this.editPanelMaxHeight) {
          height = this.editPanelMaxHeight
        }
        this.modelOfVisualizationHeight = height
        this.mouseLastPosition = { x: screenX, y: screenY }
      }
    })
  }

  /**
   * 获取数据导入和pipeline的数据集列表
   */
  private async fetchDatasetList() {
    const response = await queryDatalist({
      data: {
        projectId: this.projectId,
      },
    })
    if (response.data.code === 100) {
      VisualizationStore.setDatasetPipelineDataList(response.data.result[0])
    } else {
      VisualizationStore.setDatasetPipelineDataList({
        dataset: [],
        pipeline: [],
      })
    }
  }
}
</script>

<style lang="less">
.visualization {
  display: flex;
  height: 100%;
  overflow: hidden;
  width: 100%;
}

.side-graph-panel {
  border-right: 1px solid #ccc;
  width: 232px;
}

.layout-container {
  // box-sizing: border-box;
  // display: block;
  display: flex;
  flex: 1 1;
  flex-direction: column;
  height: 100%;
  justify-content: space-between;
  overflow: hidden;
  width: 100%;

  .panel-content {
    position: relative;
    user-select: none;

    .control-setter-box {
      background: rgba(249, 249, 252, 1);
      border-left: 1px solid #e9e9e9;
      height: 100%;
      position: absolute;
      right: 0;
      top: 0;
      transform: translateX(100%);
      transform-origin: 100% 0;
      transition: all ease-in 0.2s;
      width: 300px;
      z-index: 1000;
    }

    .resize-panel-content-height {
      border-color: rgb(103, 70, 180);
      height: 10px;
      position: absolute;
      top: 0;
      width: 100%;
      z-index: 62;

      &:hover {
        cursor: ns-resize;
      }
    }
  }
}

.view-box {
  display: block;
  height: calc(100vh - 64px);
  overflow: hidden;
  position: relative;
  width: calc(100% - 230px);

  &.open {
    width: calc (100% - 230px);

    &.hide-chart-panel {
      width: 100%;
    }

    .control-setter-box {
      transform: translateX(0);
    }

    .recommendation-box {
      width: calc(100% - 300px);
    }
  }

  &.close {
    &.hide-chart-panel {
      width: 100%;
    }
  }
}

.recommendation-box {
  bottom: 0;
  box-sizing: border-box;
  left: 21px;
  position: absolute;
  transition: all ease-in 0.2s;
  width: calc(100% - 21px);
  z-index: 999;
}
</style>
